// 云函数入口文件
const cloud = require('wx-server-sdk')
const COMMENT_TEMPLATE_ID = 'xjFRhHQCb-2GbnXKYO7NU57s7qJao22_SkRBBOOX1_4'
// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
// const dateUtils = require('date-utils')


// 云函数入口函数
exports.main = async (event, context) => {
  console.log('event', event)
  switch (event.action) {
    case 'checkPostComment': {
      return checkPostComment(event)
    }
    case 'checkimg': {
      return checkimg(event)
    }
    case 'addPostZan': {
      return addPostZan(event)
    }
    case 'addPostQrCode': {
      return addPostQrCode(event)
    }
    case 'addPostComment': {
      return addPostComment(event)
    }
    case 'addPostCollection':{
      return addPostCollection(event)
    }
    case 'deletePostCollectionOrZan': {
      return deletePostCollectionOrZan(event)
    }
    case 'addPostChildComment': {
      return addPostChildComment(event)
    }
    default: break
  }
}
/**
 * 接入内容安全
 * @param {} event 
 */
async function checkPostComment(event) {
  try {
    let result = await cloud.openapi.security.msgSecCheck({
      content: event.content
    })
    console.log(result)
    if (result.errCode == 0) {
      return true;
    }
    return false
  } catch (err) {
    return false;
  }
}
/**
 * 接入图片安全
 */
async function checkimg(event) {
  const {
    value
  } = event;
  try {
    let result = await cloud.openapi.security.imgSecCheck({
      media: {
        header: {
          'Content-Type': 'application/octet-stream'
        },
        contentType: 'image/png',
        value: Buffer.from(value)
      }
    })
    if (result.errCode == 0) {
      return true;
    }
    return false
  } catch (err) {
    return false;
  }
}
/**
 * 新增评论
 * @param {} event 
 */
async function addPostComment(event) {
  console.info("处理addPostComment")
  if (process.env.author == event.commentContent.cOpenId) {
    event.commentContent.cNickName = "作者"
  }

  event.commentContent.flag = 0
  await db.collection("mini_comments").add({
    data: event.commentContent
  });


  //如果同意
  if (event.accept == 'accept') {
    await db.collection("mini_subcribute").add({
      data: {
        templateId: COMMENT_TEMPLATE_ID,
        openId: event.commentContent.cOpenId,
        timestamp: new Date().getTime()
      }
    });
  }

  //发送消息
  await cloud.callFunction({
    name: 'messageService',
    data: {
      action: "sendSubscribeMessage",
      tOpenId: "",
      page: 'pages/details/details?id=' + event.commentContent.postId,
      nickName: event.commentContent.cNickName,
      content: event.commentContent.comment,
      createDate: event.commentContent.createDate,
      templateId: COMMENT_TEMPLATE_ID,
      cOpenId: event.commentContent.cOpenId
    }
  })
}

/**
 * 新增子评论
 * @param {} event 
 */
async function addPostChildComment(event) {



  if (process.env.author == event.comments[0].cOpenId) {
    event.comments[0].cNickName = "作者"
  }

  event.comments[0].flag = 0

  await db.collection('mini_comments').doc(event.id).update({
    data: {
      childComment: _.push(event.comments)
    }
  })


  //如果同意
  if (event.accept == 'accept') {
    await db.collection("mini_subcribute").add({
      data: {
        templateId: COMMENT_TEMPLATE_ID,
        openId: event.comments[0].cOpenId,
        timestamp: new Date().getTime()
      }
    });
  }

    //发送消息
    await cloud.callFunction({
      name: 'messageService',
      data: {
        action: "sendSubscribeMessage",
        tOpenId: event.comments[0].tOpenId,
        page: 'pages/details/details?id=' + event.postId,
        nickName: event.comments[0].cNickName,
        content: event.comments[0].comment,
        createDate: event.comments[0].createDate,
        templateId: COMMENT_TEMPLATE_ID,
        cOpenId: event.comments[0].cOpenId
      }
    })

}

/**
 * 处理文章收藏
 * @param {*} event 
 */
async function addPostCollection(event) {
  console.info("处理addPostCollection方法开始")
  console.info(event)
  let postRelated = await db.collection('mini_posts_related').where({
    openId: event.openId == undefined ? event.userInfo.openId : event.openId,
    postId: event.postId,
    type: event.type
  }).get();

   console.log('postRelated.data.length',postRelated.data.length)
  if (postRelated.data.length === 0) {
    // let date = new Date().toFormat("YYYY-MM-DD")
    return await db.collection('mini_posts_related').add({
      data: {...event}
    })
   
  }
}

/**
 * 处理赞
 * @param {} event 
 */
async function addPostZan(event) {
   console.log('addPostZan',event)
  let postRelated = await db.collection('mini_posts_related').where({
    openId: event.openId == undefined ? event.userInfo.openId : event.openId,
    postId: event.postId,
    type: event.type
  }).get();


  if (postRelated.data.length === 0) {
   return await db.collection('mini_posts_related').add({
    data:{...event}
    });
  }
  console.info(result)
}

/**
 * 移除收藏/赞
 * @param {} event 
 */
async function deletePostCollectionOrZan(event) {
  //TODO:文章喜欢总数就不归还了？
  let result = await db.collection('mini_posts_related').where({
    openId: event.openId == undefined ? event.userInfo.openId : event.openId,
    postId: event.postId,
    type: event.type
  }).remove()
  console.info(result)
}


/**
 * 新增文章二维码
 * @param {} event 
 */
async function addPostQrCode(event) {
  //let scene = 'timestamp=' + event.timestamp;
  let result = await cloud.openapi.wxacode.getUnlimited({
    scene: event.postId,
    page: 'pages/details/details'
  })

  if (result.errCode === 0) {
    let upload = await cloud.uploadFile({
      cloudPath:'海报/'+ event.postId + '.png',
      fileContent: result.buffer,
    })

    await db.collection("ChickenSoup").doc(event.postId).update({
      data: {
        qrCode: upload.fileID
      }
    });

    let fileList = [upload.fileID]
    let resultUrl = await cloud.getTempFileURL({
      fileList,
    })
    return resultUrl.fileList
  }

  return []

}
